<script setup>
import {onMounted, reactive, ref} from "vue";
import {httpGet, httpPost} from "@/utils/http.js";
// 图片压缩
import Compressor from "compressorjs";
import {ElMessage} from "element-plus";
import { CloseBold, InfoFilled, Select, UploadFilled } from "@element-plus/icons-vue";
import {MdEditor} from "md-editor-v3";
import 'md-editor-v3/lib/style.css'
import Menu from '@/views/admin/Menu.vue'
import { copyObj, dateFormat } from "@/utils/libs";
import ItemsInput from "@/components/ui/ItemsInput.vue";
import { useSharedStore } from "@/store/sharedata";

// 选项卡激活
const activeName = ref('basic')
// 系统配置
const system = ref({models: []})
const configBak = ref({})
// 数据加载动画控制
const loading = ref(true)
const systemFormRef = ref(null)
// 模型列表
const models = ref([])
// 系统公共数据
const notice = ref('')
// 菜单数据
const menus = ref([])
// MJ 模型API速度
const mjModels = ref([
  {name: "慢速（Relax）", value: "relax"},
  {name: "快速（Fast）", value: "fast"},
  {name: "急速（Turbo）", value: "turbo"},
])
const store = useSharedStore();

const rules = reactive({
  title: [{required: true, message: '请输入网站标题', trigger: 'blur',}],
  admin_title: [{required: true, message: '请输入控制台标题', trigger: 'blur',}],
  init_chat_calls: [{required: true, message: '请输入赠送对话次数', trigger: 'blur'}],
  user_img_calls: [{required: true, message: '请输入赠送绘图次数', trigger: 'blur'}],
})

onMounted(() => {
  // 加载系统配置
  httpGet('api/admin/config/get?key=system').then(res => {
    system.value = res.data
    // 把系统配置进行拷贝
    configBak.value = copyObj(system.value)
  }).catch(e => {
    ElMessage.error('加载系统配置失败：' + e.message)
  })
  // 加载系统公告
  httpGet('api/admin/config/get?key=notice').then(res => {
    notice.value = res.data['content']
  }).catch(e => {
    ElMessage.error('公共信息加载失败：' + e.message)
  })
  // 加载模型列表
  httpGet('api/admin/model/list').then(res => {
    models.value = res.data
    loading.value = false
  }).catch(e => {
    ElMessage.error('加载模型失败：' + e.message)
  })
  // 加载菜单数据
  httpGet('api/admin/menu/list').then(res => {
    menus.value = res.data
  }).catch(e => {
    ElMessage.error('加载菜单数据失败：' + e.message)
  })
})

// 保存系统配置 key 表示不同类型的系统配置
const save = (key) => {
  // 系统配置
  if (key === 'system') {
    systemFormRef.value.validate((valid) => {
      if (valid) {
        if(system.value['daily_power'] === ''){
          delete system.value['daily_power']
        }
        httpPost('api/admin/config/update', {key: key, config: system.value, config_bak: configBak.value}).then(() => {
          ElMessage.success('操作成功！')
        }).catch(e => {
          ElMessage.error('操作失败：' + e.message)
        })
      }
    })
  } else if (key === 'notice') { // 公共配置
    httpPost('api/admin/config/update', {key: key, config: {content: notice.value, updated: true}}).then(() => {
      ElMessage.success('操作成功！')
    }).catch(e => {
      ElMessage.error('操作失败：' + e.message)
    })
  }
}

const configKey = ref('')
// 上传文件前置操作，key 就表示要给那个属性进行文件上传，页面上会有多个属性都需要进行文件的上传，就需要根据这个key来标识是哪个属性，在文件上传完成之后，就需要给这个属性赋值
const beforeUpload = (key) => {
  configKey.value = key
}
// 图片上传
const uploadImg = (file) => {
  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData()
      formData.append('file', result, result.name)
      // 执行文件上传操作
      httpPost('api/admin/file/upload', formData).then(res => {
        system.value[configKey.value] = res.data.url
        ElMessage.success('上传成功')
      }).catch(e => {
        ElMessage.error('上传失败：' + e.message)
      })
    },
    error(error) {
      ElMessage.error('图片压缩失败：' + e.message)
    }
  })
}

// 编辑期文件上传处理
const onUploadImg = (files, callback) => {
  Promise.all(
      files.map(file => {
        return new Promise((rev, rej) => {
          const formData = new FormData()
          formData.append('file', file, file.name)
          // 执行上传操作
          httpPost('api/admin/file/upload', formData).then(res => rev(res)).catch(e => rej(e))
        })
      })
  ).then(res => {
    ElMessage.success({message: '上传成功', duration: 500})
    callback(res.map(item => item.data.url))
  }).catch(e => {
    ElMessage.error('上传图片失败：' + e.message)
  })
}

</script>

<template>
  <div class="system-config form" v-loading="loading">
    <el-tabs v-model="activeName" class="sys-tabs">
      <el-tab-pane label="系统配置" name="basic">
        <div class="container">
          <el-form :model="system" label-width="150px" label-position="right" ref="systemFormRef" :rules="rules">
            <el-tabs type="border-card">
              <el-tab-pane label="基础配置">
                <el-form-item label="网站标题" prop="title">
                  <el-input v-model="system['title']" />
                </el-form-item>
                <el-form-item label="控制台标题" prop="admin_title">
                  <el-input v-model="system['admin_title']" />
                </el-form-item>
                <el-form-item label="网站Slogan" prop="slogan">
                  <el-input v-model="system['slogan']" />
                </el-form-item>
                <el-form-item label="网站 LOGO" prop="logo">
                  <el-input v-model="system['logo']" placeholder="网站LOGO图片">
                    <template #append>
                      <el-upload :auto-upload="true" :show-file-list="false" @click="beforeUpload('logo')" :http-request="uploadImg">
                        <el-icon class="uploader-icon">
                          <UploadFilled/>
                        </el-icon>
                      </el-upload>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      首页背景图
                      <el-tooltip effect="dark" content="网站首页背景图" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="d-flex justify-between w-100">
                    <el-input v-model="system['index_bg_url']" placeholder="网站首页背景图片">
                      <template #append>
                        <el-upload :auto-upload="true" :show-file-list="false" @click="beforeUpload('index_bg_url')" :http-request="uploadImg">
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                    <el-button class="ml-1" type="primary" @click="system.index_bg_url = 'https://api.dujin.org/bing/1920.php'">使用动态背景</el-button>
                    <el-button class="ml-1" @click="system.index_bg_url = 'color'">使用纯色背景</el-button>
                  </div>
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      首页导航菜单
                      <el-tooltip effect="dark" content="被选中的菜单将会在首页导航栏显示" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-select
                      v-model="system['index_navs']"
                      multiple
                      :filterable="true"
                      placeholder="请选择菜单，多选"
                      style="width: 100%"
                  >
                    <el-option v-for="item in menus" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="版权信息" prop="copyright">
                  <el-input v-model="system['copyright']" placeholder="更改此选项需要获取 License 授权" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      开放注册
                      <el-tooltip raw-content effect="dark" content="关闭注册之后只能通过管理后台添加用户" placement="right">
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-switch v-model="system['enabled_register']" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      启用验证码
                      <el-tooltip raw-content effect="dark" content="启用验证码之后，注册登录都会加载行为验证码，增加安全性。此功能需要购买验证码服务才会生效。" placement="right">
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-switch v-model="system['enabled_verify']" />
                </el-form-item>
                <el-form-item label="注册方式" prop="register_ways">
                  <el-checkbox-group v-model="system['register_ways']">
                    <el-checkbox value="mobile">手机注册</el-checkbox>
                    <el-checkbox value="email">邮箱注册</el-checkbox>
                    <el-checkbox value="username">用户名注册</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="邮件域名白名单" prop="email_white_list">
                  <items-input v-model:value="system['email_white_list']"/>
                </el-form-item>
                <el-form-item label="微信客服二维码" prop="wechat_card_url">
                  <el-input v-model="system['wechat_card_url']" placeholder="微信客服二维码">
                    <template #append>
                      <el-upload :auto-upload="true" :show-file-list="false" @click="beforeUpload('wechat_card_url')" :http-request="uploadImg">
                        <el-icon class="uploader-icon">
                          <UploadFilled/>
                        </el-icon>
                      </el-upload>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      默认翻译模型
                      <el-tooltip
                          effect="dark"
                          content="选择一个默认模型来翻译提示词"
                          raw-content
                          placement="right"
                      >
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-select v-model.number="system['translate_model_id']" :filterable="true" placeholder="选择一个默认模型来翻译提示词" style="width: 100%">
                    <el-option v-for="item in models" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="开启聊天上下文">
                  <el-switch v-model="system['enable_context']" />
                </el-form-item>
                <el-form-item label="会话上下文深度">
                  <div class="tip-input-line">
                    <el-input-number v-model="system['context_deep']" :min="0" :max="10" />
                    <div class="tip">
                      会话上下文深度：在老会话中继续会话，默认加载多少条聊天记录作为上下文。如果设置为 0
                      则不加载聊天记录，仅仅使用当前角色的上下文。该配置参数必须设置需要为偶数。
                    </div>
                  </div>
                </el-form-item>
                <el-form-item >
                  <template #label>
                    <div class="label-title">
                      SD反向提示词
                      <el-tooltip
                          effect="dark"
                          content="Stable-Diffusion 绘画默认反向提示词"
                          raw-content
                          placement="right"
                      >
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input type="textarea" :rows="2" v-model="system['sd_neg_prompt']" placeholder="" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      会员充值说明
                      <el-tooltip
                          effect="dark"
                          content="会员充值页面的充值说明文字"
                          raw-content
                          placement="right"
                      >
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input type="textarea" :rows="2" v-model="system['vip_info_text']" placeholder="" />
                </el-form-item>
                <el-form-item label="MJ默认API模型" prop="mj_mode">
                  <el-select v-model="system['mj_mode']" placeholder="请选择模式">
                    <el-option v-for="item in mjModels" :value='item.value' :label="item.name" :key="item.value">{{item.name}}</el-option>
                  </el-select>
                </el-form-item>
              </el-tab-pane>

              <el-tab-pane label="算力配置">
                <el-form-item label="注册赠送算力" prop="init_power">
                  <el-input v-model.number="system['init_power']" placeholder="新用户注册赠送算力" />
                </el-form-item>
                <el-form-item label="邀请赠送算力" prop="invite_power">
                  <el-input v-model.number="system['invite_power']" placeholder="邀请新用户注册赠送算力" />
                </el-form-item>
                <el-form-item label="VIP每月赠送算力" prop="vip_month_power">
                  <el-input v-model.number="system['vip_month_power']" placeholder="VIP用户每月赠送算力" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      签到赠送算力
                      <el-tooltip effect="dark" content="每日签到赠送算力" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['daily_power']" placeholder="默认值0" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      MJ绘图算力
                      <el-tooltip
                          effect="dark"
                          content="使用MidJourney画一张图消耗算力"
                          raw-content
                          placement="right"
                      >
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['mj_power']" placeholder="" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      MJ操作算力
                      <el-tooltip
                          effect="dark"
                          content="放大，变换，重绘操作一次消耗的算力"
                          raw-content
                          placement="right"
                      >
                        <el-icon>
                          <InfoFilled/>
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['mj_action_power']" placeholder="" />
                </el-form-item>
                <el-form-item label="Stable-Diffusion算力" prop="sd_power">
                  <el-input v-model.number="system['sd_power']" placeholder="使用Stable-Diffusion画一张图消耗算力" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      DALL-E-3算力
                      <el-tooltip effect="dark" content="主要用户函数调用 DALL-E-3 进行绘画" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['dall_power']" placeholder="使用DALL-E-3画一张图消耗算力" />
                </el-form-item>
                <el-form-item label="Suno 算力" prop="suno_power">
                  <el-input v-model.number="system['suno_power']" placeholder="使用 Suno 生成一首音乐消耗算力" />
                </el-form-item>
                <el-form-item label="Luma 算力" prop="luma_power">
                  <el-input v-model.number="system['luma_power']" placeholder="使用 Luma 生成一段视频消耗算力" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      高级语音算力
                      <el-tooltip effect="dark" content="使用一次 OpenAI 高级语音对话消耗的算力" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['advance_voice_power']" placeholder="" />
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div class="label-title">
                      提示词算力
                      <el-tooltip effect="dark" content="生成AI绘图提示词，歌词，视频描述消耗的算力" raw-content placement="right">
                        <el-icon>
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <el-input v-model.number="system['prompt_power']" placeholder="" />
                </el-form-item>
              </el-tab-pane>
              <div style="padding: 10px;">
                <el-form-item>
                  <el-button type="primary" @click="save('system')">保存</el-button>
                </el-form-item>
              </div>
            </el-tabs>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="公共配置" name="notice">
        <md-editor class="mgb20" v-model="notice" :theme="store.theme" @on-upload-img="onUploadImg" />
        <el-form-item>
          <div style="padding-top: 10px;margin-left: 150px;">
            <el-button type="primary" @click="save('notice')">保存</el-button>
          </div>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="思维导图" name="mark_map">
        <md-editor class="mgb20" :theme="store.theme" v-model="system['mark_map_text']" @on-upload-img="onUploadImg" />
        <el-form-item>
          <div style="padding-top: 10px;margin-left: 150px;">
            <el-button type="primary" @click="save('system')">保存</el-button>
          </div>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="菜单配置" name="menu">
        <Menu/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style lang="stylus" scoped>
@import "../../assets/css/admin/form.styl"
@import "../../assets/css/main.styl"
.system-config {
  display flex
  justify-content center

  .sys-tabs {
    width 100%
    background-color var(--el-bg-color)
    padding 10px 20px 40px 20px
    //border: 1px solid var(--el-border-color);
  }
}
</style>